<template>
  <div class="slider-block">
    <div v-if="!addShow" class="config-list">
      <el-button  type="primary" size="medium" @click="handleAdd()">新增</el-button>
      <div class="slider-item" v-for="(item,index) in controlList" :key="item.id">
        <div class="item-head">
          <div class="head-left">
            <p class="number">{{ index + 1 }}</p>
            <p class="demonstration">{{ item.name }}</p>
          </div>
          <div class="head-right">

            <i v-show="!item.start" class="el-icon-video-play icon" @click="handleStart(item)"></i>
            <i v-show="item.start" class="el-icon-video-pause icon" @click="handleStart(item)"></i>
            <p>{{item.maxSecond}}s</p>
          </div>

        </div>
        <div class="bottom-btn">
          <el-button size="small" type="danger" @click="handleDelete(item.id)">删除</el-button>
          <el-button size="small" type="primary" @click="handleEdit(item)">编辑</el-button>
        </div>
      </div>
    </div>
    <add-control v-if="addShow" :list="list" :type="type" :data="rowData" v-on="$listeners" @startRotate="startRotate" @closeForm="handleCloseForm"/>
  </div>
</template>

<script>
import {getControlListApi,deleteControlApi} from '@/api/user'
import AddControl from "@/views/page/index/components/automatedControl/components/addControl.vue";

export default {
  name: 'automatedControl',
  components: {
    AddControl
  },
  props: {
    list: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      controlList: [],
      rowData: {},
      type: 'add',
      addShow: false,
      timers: [],
      timer: null,
    };
  },
  beforeDestroy() {
    this.clearAllTimers()
  },
  watch: {
    addShow(val) {
      if (!val) {
        this.getControlList()
      }
    },
  },
  mounted() {
    this.getControlList()
  },
  methods: {
    handleStart(row) {
      const { start, maxSecondCopy,configInfo } = row;
      // 清空所有定时器
      this.clearAllTimers();
      // 重置所有配置项的 `start` 和 `maxSecond` 属性
      this.controlList.forEach(item => {
        item.start = false;
        item.maxSecond = item.maxSecondCopy;
      });
      row.start = !start;
      if (!start) {
        // 启动定时器
        this.timer = setInterval(() => {
          row.maxSecond--;
          // 定时器结束，将 start 设为 false
          if (row.maxSecond <= 0) {
            clearInterval(this.timer);
            this.timer = null;
            row.maxSecond = maxSecondCopy;
            row.start = false;
          }
        }, 1000); // 转换为毫秒
        // 将新定时器 ID 添加到 timers 数组中
        this.startRotate(configInfo);
      }
    },
    // 清空所有定时器
    clearAllTimers() {
      this.timers.forEach(timer => {
        clearInterval(timer);
      });
      this.timers = [];
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    /**
     * 开始旋转动画。
     * @param {Array} rotateList 旋转列表，每个项包含起始角度、结束角度、持续时间（秒）和关节名称。
     */
    startRotate(rotateList) {
      rotateList.forEach((item, index) => {
        // 复制当前项避免直接修改传入列表
        const {startAngle, endAngle, second, jointName} = JSON.parse(JSON.stringify(item));
        // 发出开始旋转事件
        this.$emit('startRotate', startAngle, jointName);
        if (second) {
          // 计算毫秒级的持续时间
          const itemMilliseconds = second * 1000;
          // 计算总旋转度数
          const totalRotation = Math.abs(endAngle - startAngle);
          // 判断旋转方向
          const isClockwise = endAngle > startAngle;
          let elapsedMilliseconds = 0;
          // 定时器速度
          // let speed = Math.floor(itemMilliseconds / totalRotation);
          let speed = 10
          // 设置定时器进行旋转动画
          this.timers[index] = setInterval(() => {
            // 累计已过去的时间
            elapsedMilliseconds += speed;
            // 计算当前角度
            const currentAngle = startAngle + ((isClockwise ? 1 : -1) * (elapsedMilliseconds / itemMilliseconds) * totalRotation);
            console.log(currentAngle, 'currentAngle')
            // 发出当前角度的旋转事件
            this.$emit('startRotate', currentAngle, jointName);
            // 如果时间超过指定持续时间，则清除定时器
            if (elapsedMilliseconds >= itemMilliseconds) {
              clearInterval(this.timers[index]);
            }
          }, speed); // 定义固定时间间隔
        } else {
          // 如果没有持续时间，则直接旋转到结束角度
          this.$emit('startRotate', endAngle, jointName);
        }
      });
    },
    handleAdd() {
      this.type = 'add'
      this.addShow = true
    },
    handleEdit(row){
      this.type = 'edit'
      this.rowData = row
      this.addShow = true
    },
    handleCloseForm(){
      this.addShow = false;
    },
    getControlList() {
      getControlListApi({
        page: 1, pageSize: 10, name: ''
      }).then(res => {
        if (res.code === 0) {
          this.controlList = res.result.map((item) => {
            const { configInfo } = item
            // 最大执行时间
            const maxSecond = configInfo.reduce((max, item) => {
              return item.second > max ? item.second : max;
            }, 0);
            return {
              ...item,
              maxSecond,
              maxSecondCopy: maxSecond,
              start: false // 默认未启动
            }
          })
        }
      });
    },
    handleDelete(id){
      deleteControlApi({
        id
      }).then(res => {
        if (res.code === 0) {
          this.getControlList()
        }
      })
    }
  },
};
</script>
<style scoped lang="scss">
.slider-block {
  //font-size: 14px;
  //padding: 1vw;
  //padding: 0 10px;
  color: #606266;
  .config-list{
    padding: 10px;
    .slider-item {
      padding: 10px;
      margin: 5px 0;
      border: 1px solid #E4E7ED;

      .item-head {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        .head-left{
          display: flex;
          align-items: center;
          .number{
            height: 15px;
            width: 15px;
            border-radius: 15px;
            background: #fc5531;
            color: #fff;
            line-height: 15px;
            text-align: center;
            margin-right: 10px;
            font-size: 13px;
          }
          .demonstration{

          }
        }
        .head-right{
          display: flex;
          align-items: center;
          .icon{
            font-size: 30px;
            cursor: pointer;
          }
        }

      }
      .bottom-btn{
        text-align: right;
      }
    }
  }
}
</style>
